/**
 * 创建简单事例向导
 * @author: Xinfeng Zhao
 * 090929
 */
package edu.ccut.saturn.studio.example;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.swt.widgets.Composite;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

import edu.ccut.saturn.studio.core.exception.XMLException;
import edu.ccut.saturn.studio.core.util.eclipse.Messages;
import edu.ccut.saturn.studio.core.util.eclipse.SaturnEclipseSelectionUtil;
import edu.ccut.saturn.studio.core.util.eclipse.SaturnProjectUtil;
import edu.ccut.saturn.studio.core.util.freemaker.FreemarkerUtils;
import edu.ccut.saturn.studio.core.util.wizard.SaturnWizard;
import edu.ccut.saturn.studio.core.util.xml.SaturnW3CUtil;
import edu.ccut.saturn.studio.logic.LogicEditor;
import edu.ccut.saturn.studio.menuitem.model.MenuItem;
import edu.ccut.saturn.studio.menuitem.model.MenuItemModel;
import edu.ccut.saturn.studio.naviagtor.wizard.model.SaturnFloderWizardPage;
import edu.ccut.saturn.studio.saturndata.model.DataItem;

public class SampleWizard extends SaturnWizard {

	DataItemAtrributesVO dataItemAtrributesVO = new DataItemAtrributesVO();

	SampleWizardPage sampleWizardPage = new SampleWizardPage(
			dataItemAtrributesVO, Messages
					.getString("SampleWizard.selectDataItem")); //$NON-NLS-1$
	QueryConditionWiardPage conditionWiardPage = new QueryConditionWiardPage(
			dataItemAtrributesVO, Messages
					.getString("SampleWizard.selectQueryCondition")); //$NON-NLS-1$
	QueryListWiardPage queryListWiardPage = new QueryListWiardPage(
			dataItemAtrributesVO, Messages.getString("SampleWizard.QueryList")); //$NON-NLS-1$

	public void addPages() {

		addPage(sampleWizardPage);
		addPage(conditionWiardPage);
		addPage(queryListWiardPage);
	}

	protected String getEditorID() {
		return LogicEditor.ID;
	}

	@Override
	protected String getFileName() {
		return Messages.getString("SampleWizard.0"); //$NON-NLS-1$
	}

	@Override
	protected String getTemplatePath() {
		return Messages.getString("SampleWizard.1"); //$NON-NLS-1$
	}

	public void generateFile() {
		String saturnData = super.getValues().get(
				Messages.getString("SampleWizard.2")).toString(); //$NON-NLS-1$
		String primaryKeyName = ((DataItem) super.getValues().get(
				Messages.getString("SampleWizard.3"))).getName(); //$NON-NLS-1$
		String menuPtah = super.getValues().get(
				Messages.getString("SampleWizard.4")).toString(); //$NON-NLS-1$
		String actionKey = super.getValues().get(
				Messages.getString("SampleWizard.5")).toString(); //$NON-NLS-1$

		super.getValues().put("queryConditions", //$NON-NLS-1$
				getSelectedItems(conditionWiardPage.list_end.getItems()));
		super.getValues().put("queryList", //$NON-NLS-1$
				getSelectedItems(queryListWiardPage.list_end.getItems()));

		try {

			// 查询功能创建（包括query和querybyId）
			createSaturnFile(Messages.getString("SampleWizard.6"), saturnData); //$NON-NLS-1$
			createSaturnFile(
					Messages.getString("SampleWizard.7"), (primaryKeyName.substring(0, 1).toUpperCase() + primaryKeyName.substring(1, primaryKeyName.length()))); //$NON-NLS-1$

			// 新增功能创建
			createSaturnFile(Messages.getString("SampleWizard.8"), saturnData); //$NON-NLS-1$

			// 修改功能的创建
			createSaturnFile(Messages.getString("SampleWizard.9"), saturnData); //$NON-NLS-1$

			// 删除功能的创建
			createSaturnFile("delete", saturnData); //$NON-NLS-1$

			// 添加查询到菜单
			addActionToMenu(menuPtah, "::" + actionKey //$NON-NLS-1$
					+ "?startIndex=0&endIndex=9"); //$NON-NLS-1$

			SaturnProjectUtil.refreshProject(SaturnEclipseSelectionUtil
					.getProjectName(super.getSelection()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 添加查询的action到菜单上
	 * 
	 * @param
	 * @return
	 * @throws IOException
	 */
	private void addActionToMenu(String menuPath, String actionKey)
			throws IOException {
		try {
			Document doc = (Document) SaturnW3CUtil.getDocument(menuPath);
			MenuItemModel data = new MenuItemModel(doc);
			List<MenuItem> modleMenuItems = data.getMenu().getChildren();
			Node menuItemNode = null;
			List<Node> menuItems = SaturnW3CUtil.getChildrenNode(doc
					.getDocumentElement());
			int i = 1;
			if (modleMenuItems.get(0).getChildren().size() != 0) {
				i = modleMenuItems.get(0).getChildren().size() + 1;
			}

			for (Node menuItem : menuItems) {
				if ("".equals(SaturnW3CUtil.getNodeAttributeValue(menuItemNode, //$NON-NLS-1$
						"parentId"))) { //$NON-NLS-1$
					menuItemNode = menuItem;
				}
			}

			Node newMenuItemNode = SaturnW3CUtil.createChildNode(menuItemNode,
					MenuItemModel.MENUITEMS_ELEMENT_MENUITEM, null);

			SaturnW3CUtil.createAttribute(newMenuItemNode,
					MenuItemModel.MENUITEM_ATTRIBUTE_ID, System
							.currentTimeMillis()
							+ ""); //$NON-NLS-1$
			SaturnW3CUtil.createAttribute(newMenuItemNode,
					MenuItemModel.MENUITEM_ATTRIBUTE_LABEL, Messages
							.getString("SampleWizard.example")); //$NON-NLS-1$
			SaturnW3CUtil.createAttribute(newMenuItemNode,
					MenuItemModel.MENUITEM_ATTRIBUTE_ORDER, i + ""); //$NON-NLS-1$
			SaturnW3CUtil.createAttribute(newMenuItemNode,
					MenuItemModel.MENUITEM_ATTRIBUTE_PARENT_ID, "1"); //$NON-NLS-1$
			SaturnW3CUtil.createAttribute(newMenuItemNode,
					MenuItemModel.MENUITEM_ATTRIBUTE_PATH, actionKey);

			SaturnW3CUtil.format(menuItemNode);

			OutputStream out = new FileOutputStream(new File(menuPath));
			Writer wr = new OutputStreamWriter(out, "UTF-8"); //$NON-NLS-1$
			SaturnW3CUtil.writeDocument(doc, new File(menuPath).getPath());
			wr.close();
			out.close();

		} catch (XMLException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 根据传递的参数不同创建不同的功能
	 * 
	 * @param actionType
	 *            （query、delete···）
	 * @param saturnData
	 */
	private void createSaturnFile(String actionType, String saturnData) {

		// 创建logic
		checkFilePath(SaturnEclipseSelectionUtil.getFullPath(super
				.getSelection())
				+ File.separator, "logic"); //$NON-NLS-1$

		String file = SaturnEclipseSelectionUtil.getFullPath(super
				.getSelection())
				+ File.separator + "logic" //$NON-NLS-1$
				+ File.separator + actionType + saturnData + ".logic"; //$NON-NLS-1$
		String templatePath = "template/examples/" + actionType + "Logic"; //$NON-NLS-1$ //$NON-NLS-2$
		FreemarkerUtils.writeTemplateToFile(templatePath, super.getValues(),
				file);

		// 创建action
		checkFilePath(SaturnEclipseSelectionUtil.getFullPath(super
				.getSelection())
				+ File.separator, "action"); //$NON-NLS-1$

		String actionFile = SaturnEclipseSelectionUtil.getFullPath(super
				.getSelection())
				+ File.separator + "action" //$NON-NLS-1$
				+ File.separator + actionType + saturnData + ".action"; //$NON-NLS-1$
		String actionTemplatePath = "template/examples/" + actionType //$NON-NLS-1$
				+ "Action"; //$NON-NLS-1$
		FreemarkerUtils.writeTemplateToFile(actionTemplatePath, super
				.getValues(), actionFile);

		// 创建query时的jsp
		if ("query".equals(actionType)) { //$NON-NLS-1$
			checkFilePath(SaturnEclipseSelectionUtil.getFullPath(super
					.getSelection())
					+ File.separator, "web"); //$NON-NLS-1$

			// 查询的jsp
			String queryJspPath = SaturnEclipseSelectionUtil.getFullPath(super
					.getSelection())
					+ File.separator + "web" //$NON-NLS-1$
					+ File.separator + "query" //$NON-NLS-1$
					+ saturnData + ".jsp"; //$NON-NLS-1$
			String queryJspTemplatePath = "template/examples/queryJsp"; //$NON-NLS-1$
			FreemarkerUtils.writeTemplateToFile(queryJspTemplatePath, super
					.getValues(), queryJspPath);

			// 新增的jsp
			String addJspPath = SaturnEclipseSelectionUtil.getFullPath(super
					.getSelection())
					+ File.separator + "web" //$NON-NLS-1$
					+ File.separator + "add" //$NON-NLS-1$
					+ saturnData + ".jsp"; //$NON-NLS-1$
			String addJspTemplatePath = "template/examples/addJsp"; //$NON-NLS-1$
			FreemarkerUtils.writeTemplateToFile(addJspTemplatePath, super
					.getValues(), addJspPath);
			// 修改的jsp
			String updateJspPath = SaturnEclipseSelectionUtil.getFullPath(super
					.getSelection())
					+ File.separator + "web" //$NON-NLS-1$
					+ File.separator + "update" //$NON-NLS-1$
					+ saturnData + ".jsp"; //$NON-NLS-1$
			String updateJspTemplatePath = "template/examples/updateJsp"; //$NON-NLS-1$
			FreemarkerUtils.writeTemplateToFile(updateJspTemplatePath, super
					.getValues(), updateJspPath);
		}

	}

	/**
	 * 检查要创建的文件的上层文件夹是否存在不存在自动创建
	 */
	private void checkFilePath(String FloderPtah, String type) {
		FloderPtah = FloderPtah + type;

		File Floder = new File(FloderPtah);
		if (!Floder.exists()) {
			Floder.mkdir();

			String templatePath = "template/saturnfloder.ftl"; //$NON-NLS-1$
			Map<String, Object> values = new HashMap<String, Object>();

			if (type.equals("logic")) { //$NON-NLS-1$
				values.put(SaturnFloderWizardPage.SATURN_FLODER_NAME, Messages
						.getString("SampleWizard.logicFloder")); //$NON-NLS-1$

			} else if (type.equals("action")) { //$NON-NLS-1$
				values.put(SaturnFloderWizardPage.SATURN_FLODER_NAME, Messages
						.getString("SampleWizard.actionFloder")); //$NON-NLS-1$
			} else {
				values.put(SaturnFloderWizardPage.SATURN_FLODER_NAME, Messages
						.getString("SampleWizard.webFolder")); //$NON-NLS-1$
			}

			values.put(SaturnFloderWizardPage.SATURN_FLODER_TYPE, type);
			values.put(SaturnFloderWizardPage.SATURN_FLODER_DESCRIPTION, ""); //$NON-NLS-1$
			values.put(SaturnFloderWizardPage.SATURN_FLODER_VERSION, "1.0"); //$NON-NLS-1$
			values.put(SaturnFloderWizardPage.SATURN_FLODER_TIME, System
					.currentTimeMillis()
					+ ""); //$NON-NLS-1$

			String file = FloderPtah + File.separator + ".saturn"; //$NON-NLS-1$
			FreemarkerUtils.writeTemplateToFile(templatePath, values, file);
		}
	}

	public void createPageControls(Composite comp) {
	}

	/**
	 * 根据所选择的字段名称，过滤数据项字段的集合
	 * 
	 * @param itemNames
	 * @return
	 */
	public List<DataItem> getSelectedItems(String[] itemNames) {

		List<DataItem> items = dataItemAtrributesVO.getDataItems();
		List<DataItem> itemsInEnd = new ArrayList<DataItem>();

		for (int i = 0; i < itemNames.length; i++) {
			for (DataItem dataitem : items) {
				if (dataitem.getName().equals(itemNames[i])) {
					itemsInEnd.add(dataitem);
				}
			}
		}
		return itemsInEnd;
	}

	public String getWindowTitle() {
		return Messages.getString("SampleWizard.createSample"); //$NON-NLS-1$
	}

	public boolean canFinish() {
		if (this.getContainer().getCurrentPage() != queryListWiardPage) {
			return false;
		}
		return super.canFinish();
	}
}
